package com.geqian.structure.db;

import com.geqian.structure.common.dto.DataSourceDto;
import com.geqian.structure.pojo.DatabaseInfo;
import com.geqian.structure.utils.SpringContextUtils;
import com.ibm.db2.jcc.am.DisconnectNonTransientConnectionException;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * @author geqian
 * @date 20:16 2023/1/4
 */
public class DbConnection {

    private static volatile Connection connection;

    private static DataSourceDto dataSourceInfo;


    public static void setDataSource(DataSourceDto dataSourceInfo) {
        DbConnection.dataSourceInfo = dataSourceInfo;
    }

    public static void createConnection() {
        try {
            DatabaseInfo databaseInfo = SpringContextUtils.getBean(dataSourceInfo.getDatabaseType(), DatabaseInfo.class);
            databaseInfo.appendUrlSuffix(dataSourceInfo.getDatabase());
            Class.forName(databaseInfo.getDriverClass());
            String url = databaseInfo.getUrl(dataSourceInfo.getIp(), dataSourceInfo.getPort());
            DriverManager.setLoginTimeout(30);
            connection = DriverManager.getConnection(url, dataSourceInfo.getUsername(), dataSourceInfo.getPassword());
            JDBCUtils.setDatabaseInfo(databaseInfo);
            System.out.println("连接创建成功");
        }catch (DisconnectNonTransientConnectionException e){
            throw new RuntimeException("连接超时");
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("请检查连接信息是否有误");
        }
    }

    public static Connection getConnection() {
        if (connection == null) {
            synchronized (DbConnection.class) {
                if (connection == null) {
                    createConnection();
                }
            }
        }
        return connection;
    }


    public static DataSourceDto getDataSourceInfo() {
        return dataSourceInfo;
    }

    public static void clearConnection() {
        DbConnection.connection = null;
    }
}
